#include "StdAfx.h"
#include "LThread.h"

DWORD __stdcall LThreadFunction( LPVOID who );

LThread::LThread(void)
{
	TRACE(_T("---- thread.create: %d \n"), int(this));

	mhd = INVALID_HANDLE_VALUE;

	mthreadrun = true;
	mthreadstoped = false;
	miscreate = false;
	midthread = 0;

	miswork = false;
}
LThread::~LThread(void)
{
	//exit();
	TRACE(_T("---- thread.destory: id=%d, %d \r\n"), midthread, (int)this);
}
int LThread::init()
{
	int ret = 0;
	createThread();
	return ret;
}
void LThread::exit()
{
	stWork(false);
	stopThread();
}
void LThread::createThread()
{
	mhd = ::CreateThread( NULL, 0, LThreadFunction, this, 0, &midthread );
	if( isHandle() )	::CloseHandle( mhd );

	//TRACE(_T("createThread: %d\n"), (int)this);
}
void LThread::stopThread()
{
	if ( isHandle() )
	{
		setThreadRun( false );
		while( !isThreadStoped() )	// wait thread until stop;
			Sleep(1);	
	}
}


DWORD __stdcall LThreadFunction( LPVOID who )
{
	int err = 0; 
	LThread * lt = (LThread * ) who;
	VERIFY( lt );
	
	int d =0;

	while( lt->isThreadRun() )
	{
		//if( lt->threadFun() < 0 )
		//{
		//	lt->setThreadRun( false );
		//	break;
		//}
		d = lt->threadFun();
		Sleep(10);

	}
	lt->setStoped();

	TRACE(TEXT("thread stopped: %d\r\n"),(int)who);
	return 0;
}
int LThread::threadFun()
{
	int ret = 0;
	int d = 0;
	if ( isWork() )
	{
		d = onStart();
		if( d >=0 )
		{
			d = workLoop();
			if( d < 0 )
			{
				--ret;
			}
		}
		else
		{
			--ret;
		}
		onStop();
	}

	//glog->logF(TEXT("LThread:threadFun();"), ret );
	return ret;
}
int LThread::onStart()
{
	int ret = 0;
	return ret;
}
void LThread::onStop()
{

}
int LThread::workLoop()
{
	int ret = 0;
	int d = 0;

	while ( isWork() && (ret >=0) )
	{
		d = start();
		if( d >0 ) 
		{
			d = work();
			if( d < 0 )
			{
				--ret;
			}
		}
		else if( d < 0 )
		{
			--ret;
		}
		onStop();

		if( d == 0)
		{
			Sleep(1);
		}
	}
	if( ret < 0 )
	{
		stWork( false );
	}

	//glog->logF(TEXT("LThread:procLoop();"), ret );
	return ret;
}
int LThread::start()
{
	int ret = 0;
	return ret;
}
void LThread::stop()
{

}
int LThread::work()
{
	int ret = 0;
	return ret;
}




